package com.itheima.controller;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CateGoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CateGoryService cateGoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     * 使用DTO
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> pageDtoInfo = new Page<>();

//        条件查询器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, queryWrapper);
//对象拷贝
        BeanUtils.copyProperties(pageInfo, pageDtoInfo, "records");
        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = cateGoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;

        }).collect(Collectors.toList());

        pageDtoInfo.setRecords(list);

        return R.success(pageDtoInfo);

    }

    /**
     * 新增菜品
     *
     * @param dishDto（数据传输对象）页面传回来的数据和实体类不是一一对应
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("新增菜品：{}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        //        新增菜品之后要清楚redis的缓存，重新加载进入缓存
        //Set keys = redisTemplate.keys("dish_*");全部清理
//        精确清理
     /*   String key ="dish_"+dishDto.getCategoryName()+"_1";
        redisTemplate.delete(key);*/

        return R.success("新增菜品成功");

    }

    /**
     * 修改时根据id的回显（菜品和口味信息）
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishServiceBYIdWithFlavor = dishService.getBYIdWithFlavor(id);
        return R.success(dishServiceBYIdWithFlavor);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        //更新菜品之后要清楚redis的缓存，重新加载进入缓存
        //Set keys = redisTemplate.keys("dish_*");全部清理
//        精确清理
      /*  String key ="dish_"+dishDto.getCategoryName()+"_1";
        redisTemplate.delete(key);*/

        return R.success("修改成功");
    }

    /**
     * 删除商品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> delete(Long ids) {
        log.info("ids:{}", ids);

//        删除基本信息
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getId, ids);
        dishService.remove(queryWrapper);
//        删除口味
        LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(DishFlavor::getDishId, ids);
        dishFlavorService.remove(queryWrapper1);

   /*     //  删除菜品之后要清redis的缓存，重新加载进入缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        return R.success("删除成功");

    }


    @PostMapping("/status/{status}")
    public R<String> putStatus(@PathVariable("status") int status, @RequestParam List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        List<Dish> dishes = dishService.list(queryWrapper);
        for (Dish dish : dishes) {
            if (dish !=null){
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return R.success("修改成功");
    }

    /**
     * 套餐添加菜品时，查询菜品
     * 传过来的id，boot会自动封装为dish对象
     *
     * @param dish
     * @return
     */
/*    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        等值查询
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        只查可以售卖的(1:起售状态）
        queryWrapper.eq(Dish::getStatus,1);
//        排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        查询
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/

    /**
     * 套餐添加菜品时，查询菜品
     * 传过来的id，boot会自动封装为dish对象
     * 移动端追加一个选择规格的展示，追加一个口味数据flavor
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> list(Dish dish) {
/*//        把下面定义提上来
        List<DishDto>  dishDtoList =null;
//        动态的设计key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //1.先从redis中获取菜品，根据id
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);

        //2.如果存在直接返回，不查数据库
        if (dishDtoList !=null){
            //存在
            return R.success(dishDtoList);
        }
        //3.不存在，查数据库*/

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        等值查询
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        只查可以售卖的(1:起售状态）
        queryWrapper.eq(Dish::getStatus,1);
//        排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        查询
        List<Dish> list = dishService.list(queryWrapper);

//        多增加一个口味属性，拷贝dish，做成dishDto
        List<DishDto> dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
//            当前菜品的id
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

      /*    //4.走到这里说明缓存没有，加缓存
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);*/

        return R.success(dishDtoList);
    }


}
